package edu.pku.sei.ocl.utilities;

import java.util.HashMap;

import org.eclipse.emf.common.util.BasicEList;
import org.eclipse.emf.common.util.EList;


public class CacheUtil {
	HashMap<Object,Object> cacheData = new HashMap<Object,Object>(10);
	
	@SuppressWarnings("unchecked")
	public void put(Object value, Object... key){
		HashMap<Object,Object> data = cacheData;
		
		int i=0;
		
		for(i=0;i<key.length-1;i++){
			Object oldData = data.get(key[i]);
			if(oldData==null){
				oldData = new HashMap<Object,Object>(10);
				data.put(key[i], oldData);
			}
			
			assert((oldData instanceof HashMap<?,?>));
			
			data = (HashMap<Object, Object>) oldData;
		}
		
		data.put(key[key.length-1], value);
	}
	
	@SuppressWarnings("unchecked")
	public void add(Object value,Object... key){
		HashMap<Object,Object> data = cacheData;
		
		int i=0;
		
		for(i=0;i<key.length-1;i++){
			Object oldData = data.get(key[i]);
			if(oldData==null){
				oldData = new HashMap<Object,Object>(10);
				data.put(key[i], oldData);
			}
			
			assert((oldData instanceof HashMap<?,?>));
			
			data = (HashMap<Object, Object>) oldData;
		}
		
		EList<Object> list = null;
		Object currentValue = data.get(key[key.length-1]);
		
		if(currentValue == null)
			list = new BasicEList<Object>(5);
		else if(currentValue instanceof EList){
			list = (EList<Object>) currentValue;
		}
		else assert false;
		
		list.add(value);
		
		data.put(key[key.length-1], list);
	}
	
	@SuppressWarnings("unchecked")
	public Object get(Object... key){
		HashMap<Object,Object> data = cacheData;
		
		int i=0;
		
		for(i=0;i<key.length-1;i++){
			Object oldData = data.get(key[i]);
			if(oldData==null)
				return null;
			
			assert((oldData instanceof HashMap<?,?>));
			
			data = (HashMap<Object, Object>) oldData;
		}
		
		return data.get(key[key.length-1]);
	}

	public void clear() {
		cacheData.clear();
	}

}
